package me.magicall.test.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Monitor {

	public static interface LongRun {
		Object getCurStatus();

	}

	private final int port;
	private volatile ServerSocket serverSocket;

	public Monitor(final int port) {
		super();
		this.port = port;
	}

	public boolean isOpen() {
		System.out.println("isOpen serverSocket:" + serverSocket);
		return serverSocket != null && !serverSocket.isClosed();
	}

	public void open() {

		if (!isOpen()) {
			System.out.println("QujingMonitor is not open!");

			new Thread(new Runnable() {
				@Override
				public void run() {
					openMonitorSocket();
				}
			}).start();
		}
	}

	public void close() {
		if (serverSocket != null) {
			try {
				serverSocket.close();
			} catch (final IOException e) {
				e.printStackTrace();
			}
		}
	}

	private void openMonitorSocket() {
		// if (serverSocket != null && serverSocket.isClosed()) {
		// return;
		// }
		// System.out.println("开启一个新线程来连接socket");
		// try {
		// serverSocket = new ServerSocket(port);
		// Socket socket;
		// while (!serverSocket.isClosed() && (socket = serverSocket.accept())
		// != null) {
		// final InputStream inputStream = socket.getInputStream();
		// final OutputStream outputStream = socket.getOutputStream();
		// checkOrder(inputStream, outputStream);
		// socket.close();
		// }
		// } catch (final IOException e) {
		// e.printStackTrace();
		// } finally {
		// if (serverSocket != null) {
		// try {
		// serverSocket.close();
		// } catch (final IOException e) {
		// e.printStackTrace();
		// }
		// }
		// }
		// ////////////////////////////////调试使用////////////////////////////
		if (serverSocket != null && serverSocket.isClosed()) {
			return;
		}
		System.out.println("开启一个新线程来连接socket");
		try {
			serverSocket = new ServerSocket(port);
			System.out.println("openMonitorSocket()中的serverSocket" + serverSocket + ":" + port);
			Socket socket = serverSocket.accept();
			System.out.println("!serverSocket.isClosed()" + serverSocket.isClosed()
					+ "(socket = serverSocket.accept()) != null" + (socket != null));
			while (!serverSocket.isClosed() && socket != null) {
				System.out.println("客户端socket已经连接上！");
				final InputStream inputStream = socket.getInputStream();
				final OutputStream outputStream = socket.getOutputStream();
				checkOrder(inputStream, outputStream);
				socket.close();
				System.out.println("客户端socket已经断开！");
				socket = serverSocket.accept();
			}
		} catch (final IOException e) {
			e.printStackTrace();
		} finally {
			if (serverSocket != null) {
				try {
					serverSocket.close();
				} catch (final IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	protected void checkOrder(final InputStream inputStream, final OutputStream outputStream) {

	}
}
